#!/bin/bash

# 确保脚本在遇到错误时立即退出
set -x
set -e
set -o pipefail

# 检查是否为root用户
if [[ "$(whoami)" != "root" ]]; then
  echo "请使用root用户运行此脚本。"
  exit 1
fi

source ./common.sh

hosts_file=./user_conf/hosts_file.conf

OLD_IFS=$IFS

IFS=$'\n'

# 检查并安装sshpass
if ! command -v sshpass &> /dev/null; then
    echo "sshpass未安装，正在自动安装..."
    sudo yum install -y sshpass
    echo "sshpass已安装成功。"
else
    echo "sshpass已安装，继续执行下面的代码..."
fi

# 修改本机的hosts文件
echo "正在更新本地 /etc/hosts 文件..."

# 逐行处理 hosts_content 中的内容
while read -r line; do
    # 跳过空白行
    if [[ -z "${line// /}" ]]; then
		echo "跳过空白行"
        continue
    fi

    ip=$(echo "$line" | awk '{print $1}')
    hostname=$(echo "$line" | awk '{print $2}')

    # 判断主机名是否存在
    if grep -q -E "${hostname}" /etc/hosts; then
        # 存在，则删除原来的
        sudo sed -i "/\b${hostname}\b/d" /etc/hosts
    fi
    # 添加新的主机名映射
    echo "${ip} ${hostname}" | sudo tee -a /etc/hosts > /dev/null
done < "${hosts_file}"

echo "本地 /etc/hosts 文件已成功更新。"

echo "===本机hosts文件内容==="
cat /etc/hosts
echo "===本机hosts文件内容==="

# 遍历服务器列表
for server in "${servers[@]}"; do
  # 关闭并禁用firewalld
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "systemctl stop firewalld && systemctl disable firewalld.service"
done

#删除用户及目录
for server in "${servers[@]}"; do
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "pkill -u ${new_user} >/dev/null 2>&1 || true"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "userdel -r ${new_user} >/dev/null 2>&1 || true"
  
    user_id=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "id -u "${new_user}" 2>/dev/null || true")

	if [ -z "${user_id}" ]; then
	  echo "用户删除成功 ${server}"
	else
	  echo "用户删除失败 ${server}"
	fi
done

# 遍历服务器列表
for server in "${servers[@]}"; do
  # 检查用户是否存在，不存在则创建
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "id -u ${new_user} &>/dev/null || useradd ${new_user}"

  # 修改用户密码
  echo "开始修改密码 ${server} ${new_user}:${new_user_password}"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "echo '${new_user}:${new_user_password}' | chpasswd"
  echo "密码修改完成 ${server} ${new_user}:${new_user_password}"
done

# 在服务器上执行以下操作
for server in "${servers[@]}"; do
  echo "开始检查root权限 ${server} ${new_user}"

  grep_result=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "grep -E '^${new_user}[[:space:]]+ALL=\(ALL\)[[:space:]]+NOPASSWD:ALL' /etc/sudoers" 2>/dev/null || true)

  echo "grep_result结果为：${grep_result}"

  if [ -z "${grep_result}" ]; then
    echo "开始为 ${server} ${new_user} 用户添加root权限"

    # 获取root权限所在行号
    root_line_number=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "cat -n /etc/sudoers | grep -E 'root[[:space:]]+ALL=\(ALL\)[[:space:]]+ALL' | awk '{print \$1}'")

    # 计算新用户权限应插入的行号
    new_user_line_number=$((root_line_number + 1))

    # 将新用户权限插入到计算出的行号
    sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "sed -i '${new_user_line_number}i${new_user}   ALL=(ALL)     NOPASSWD:ALL' /etc/sudoers"

    echo "${server} ${new_user} 用户添加root权限完成"
  else
    echo "检查root权限结束 ${server} ${new_user} 用户已具有root权限"
  fi
done

# 在服务器上执行以下操作
for server in "${servers[@]}"; do
  # 创建目录
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "mkdir -p /opt/module"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "mkdir -p /opt/software"

  # 修改目录所有者和所属组
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "chown ${new_user}:${new_user} /opt/module"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "chown ${new_user}:${new_user} /opt/software"
done

# 遍历服务器列表
for server in "${servers[@]}"; do
  # 配置hosts映射文件
  IFS=$OLD_IFS
  IFS=$'\n'

  echo "开始配置 ${server} hosts映射文件"

  while read -r entry; do
    echo "开始配置${server} hosts映射文件,进入while循环 ${entry}"

    ip=$(echo "${entry}" | awk '{print $1}')
    hostname=$(echo "${entry}" | awk '{print $2}')

    # 判断主机名是否存在并删除原有条目
    sshpass -p "${root_password}" ssh -n -o StrictHostKeyChecking=no root@"${server}" "if grep -q -E '\b${hostname}\b' /etc/hosts; then sudo sed -i '/\b${hostname}\b/d' /etc/hosts; fi"

    # 添加新的主机名映射
    sshpass -p "${root_password}" ssh -n -o StrictHostKeyChecking=no root@"${server}" "echo '${ip} ${hostname}' | sudo tee -a /etc/hosts > /dev/null"
  done < "${hosts_file}"
done

IFS=$OLD_IFS

#删除.ssh
for server in "${servers[@]}"; do
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "rm -rf /home/${new_user}/.ssh/*"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "rm -rf /root/.ssh/*"
done

#配置PubkeyAuthentication yes
for server in "${servers[@]}"; do

  line_number=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "awk '/PubkeyAuthentication/{print NR; exit}' /etc/ssh/sshd_config")
  
  line_number2=$((line_number + 1))
  
  rsa_auth_line_number=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "awk '/RSAAuthentication/{print NR; exit}' /etc/ssh/sshd_config")

	if [[ -n "${rsa_auth_line_number}" ]]; then
	  # 使用 rsa_auth_line_number 进行操作，在 sed 命令中删除该行
	  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "sed -i \"${rsa_auth_line_number}d\" /etc/ssh/sshd_config"
	fi
  
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "sed -i \"${line_number}d\" /etc/ssh/sshd_config"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "sudo sed -i \"${line_number}iPubkeyAuthentication yes\" /etc/ssh/sshd_config"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "sudo sed -i \"${line_number2}iRSAAuthentication yes\" /etc/ssh/sshd_config"
done

# 遍历服务器列表
for server in "${servers[@]}"; do

	echo "开始为新用户生成SSH密钥并配置免密登录 ${server}"

  # 为新用户生成SSH密钥并配置免密登录
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "yes | ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q"
  new_user_public_key=$(sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "cat ~/.ssh/id_rsa.pub")

  # 为root用户生成SSH密钥并配置免密登录
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "yes | ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q"
  root_public_key=$(sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "cat ~/.ssh/id_rsa.pub")

  for other_server in "${servers[@]}"; do
    # 配置新用户的免密登录
	
	echo "开始向 ${new_user}@${other_server} 复制公钥"
	
    sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${other_server}" "mkdir -p ~/.ssh && echo '${new_user_public_key}' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

	echo "${new_user}@${other_server} 复制公钥完成"

    # 配置root用户的免密登录
    sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${other_server}" "mkdir -p ~/.ssh && echo '${root_public_key}' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
  done
done

# 遍历服务器列表更新known_hosts文件
for server in "${servers[@]}"; do
  for other_server in "${servers[@]}"; do
    # 自动添加服务器公钥到当前服务器的known_hosts
    sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no root@"${server}" "ssh-keyscan ${other_server} >> /root/.ssh/known_hosts"
    sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "ssh-keyscan ${other_server} >> /home/${new_user}/.ssh/known_hosts"
  done
done

#给.ssh目录权限
for server in "${servers[@]}"; do
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "chmod 700 /root/.ssh"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "chmod 700 /home/${new_user}/.ssh"
  
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "chmod 600 /root/.ssh/authorized_keys"
  sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "chmod 600 /home/${new_user}/.ssh/authorized_keys"
done

#重新启动SSH服务使更改生效
for server in "${servers[@]}"; do

  if [ "${server}" != "${master_server}" ]; then
    sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${server}" "sudo service sshd restart"
	echo "重新启动SSH服务成功 ${server}"
  fi
  
done

sshpass -p "${root_password}" ssh -o StrictHostKeyChecking=no "root@${master_server}" "sudo service sshd restart"

echo "已完成所有服务器的firewalld、用户、目录、主机映射配置以及为root用户和${new_user}设置无密码SSH登录。"